package com.example.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.es.dataobject.BlogDO;
import com.example.es.service.IndexService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public String prepareData() {
        List<BlogDO> blogDOS = new ArrayList<>();
        blogDOS.add(new BlogDO("ElasticSearch究竟是个什么东西", "Java鱼仔"));
        blogDOS.add(new BlogDO("SpringBoot+SpringSecurity实现基于真实数据的授权认证", "Java鱼仔"));
        blogDOS.add(new BlogDO("Dubbo两小时快速上手教程（直接代码、Spring、SpringBoot）", "Java鱼仔"));
        blogDOS.add(new BlogDO("浅析五种最常用的Java加密算法", "Java鱼仔"));
        blogDOS.add(new BlogDO("Java程序员需要知道的操作系统知识汇总", "Java鱼仔"));
        blogDOS.add(new BlogDO("一步步教你如何在SpringBoot项目中引入支付功能", "Java鱼仔"));
        blogDOS.add(new BlogDO("Zookeeper实现分布式锁的原理是什么？", "Java鱼仔"));
        blogDOS.add(new BlogDO("一个成熟的Java项目如何优雅地处理异常", "Java鱼仔"));
        blogDOS.add(new BlogDO("基于SpringBoot实现文件的上传下载", "Java鱼仔"));
        blogDOS.add(new BlogDO("如何用Java写一个规范的http接口？", "Java鱼仔"));
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        blogDOS.stream().forEach(x -> {
            bulkRequest.add(new IndexRequest("blog_index").source(JSON.toJSONString(x), XContentType.JSON));
        });
        BulkResponse responses = null;
        try {
            responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return responses.status() + "";
    }

    @Override
    public List<Map<String, Object>> searchByKeywords(String keywords, Pageable pageable) {
        return searchData(keywords, pageable);
    }


    public List<Map<String,Object>> searchData(String keywords, Pageable pageable){
        //生成搜索对象
        SearchRequest request = new SearchRequest("blog_index");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置分页参数
        searchSourceBuilder.from(pageable.getPageNumber());
        searchSourceBuilder.size(pageable.getPageSize());

        //高亮构造器
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        //高亮查询字段
        highlightBuilder.field("title");
        //是否将所有匹配到的字段高亮显示，false表示只显示一个
        highlightBuilder.requireFieldMatch(false);
        //高亮的标签
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);


        //设置搜索的字段
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keywords);
        searchSourceBuilder.query(matchQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));
        request.source(searchSourceBuilder);
        SearchResponse search=null;
        try {
            search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将结果返回
        List<Map<String,Object>> result=new ArrayList();
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit searchHit:hits){
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            if (title!=null){
                StringBuilder highLightTitle=new StringBuilder();
                Text[] texts = title.fragments();
                for(Text text:texts){
                    highLightTitle.append(text);
                }
                sourceAsMap.put("title",highLightTitle);
            }
            result.add(sourceAsMap);
        }
        return result;
    }

}
